require.config({
	baseUrl: "./javascripts/library",
	path: {
		axios: "axios",
		countdown: "countdown",
		jquery: "jquery",
		slider: "slider",
		swiper: "swiper",
		tabs: "tabs",
	},
});
require(["axios", "jquery", "tabs"], function (axios, $, tabs) {
	let id = location.search.split("=")[1];
	axios
		.get("/goods/goodsdetail", {
			params: {
				id,
			},
		})
		.then((response) => {
			let data = response.data;
			if (data.success) {
				let main_img_container = $("#main .preview .main-img");
				let btns_container = $("#main .preview .spec-list .spec-items ul");
				let product_id = data.data[0].id;
				let temp1 = "";
				let temp2 = "";
				let main_imgs_src_list = JSON.parse(data.data[0].picture)
					.slice(1)
					.map((el) => {
						return el.src;
					});

				main_imgs_src_list.forEach((el, index) => {
					if (index == 0) {
						temp1 += `<img src=${el} alt="" class="display" goods-id="${product_id}"/>`;
						temp2 += `<li class="active">
										<img src=${el} alt="" goods-id="${product_id}"/>
									</li>`;
					} else {
						temp1 += `<img src=${el} alt="" goods-id="${product_id}"/>`;
						temp2 += `<li>
										<img src=${el} alt="" goods-id="${product_id}"/>
									</li>`;
					}
				});
				main_img_container.html(temp1);
				btns_container.html(temp2);
				let btns = $("#main .preview .spec-list .spec-items li");
				let items = $("#main .preview .main-img img");
				tabs.tabs({
					btns,
					items,
					ev: "hover",
				});
			}
		});
});

require(["jquery"], function ($) {
	let add = $("#main .choose-btns .btn-add");
	let sub = $("#main .choose-btns .btn-reduce");
	let buy_num = $("#main .choose-btns #buy-num");
	add.on("click", function (ev) {
		ev.preventDefault();
		let count = Number(buy_num.attr("value"));
		buy_num.attr("value", count + 1);
	});
	sub.on("click", function (ev) {
		ev.preventDefault();
		let count = Number(buy_num.attr("value"));
		if (count == 1) return;
		buy_num.attr("value", count - 1);
	});
});

require(["jquery"], function ($) {
	let add = $("#main .choose-btns #incart");

	add.on("click", function (ev) {
		ev.preventDefault();
		let cart = localStorage.getItem("cart");
		let product_id = $("#main .preview .main-img img").attr("goods-id");
		let product_num = Number($("#main .choose-btns #buy-num").attr("value"));
		if (!cart) {
			cart = [];
			cart.push({
				id: product_id,
				num: product_num,
			});
			localStorage.setItem("cart", JSON.stringify(cart));
		} else {
			cart = JSON.parse(cart);
			let is_exist = cart.some((el) => {
				return el.id == product_id;
			});
			if (is_exist) {
				let index = cart.findIndex((el) => {
					return el.id == product_id;
				});
				cart[index].num = Number(cart[index].num) + product_num;
			} else {
				cart.push({ id: product_id, num: product_num });
			}
			localStorage.setItem("cart", JSON.stringify(cart));
		}
	});
});
